package com.example.demoserver.service;

import com.example.demoserver.controller.Util;
import com.example.demoserver.entity.InteAppalarm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Service
public class TaskService {
    private ScheduledFuture<?> future;
    InteAppalarmService inteAppalarmService;
    private volatile int Ltype = 0;
    String[] types = {"无异常", "运行状态异常", "通信异常", "安全漏洞异常", "版本过低异常", "微服务状态异常"};
    String[] str1={"设备在线服务未启动","网络异常"};
    String[] str2={"接收数据为空","数据格式错误","数据不属于该设备"};
    String[] str3={"出现安全漏洞"};
    String[] str4={"版本过低异常"};
    String[] str5={"设备管理APP状态异常","生产管理APP状态异常","运营管理APP状态异常"};
    @Autowired
    private ScheduledExecutorService executor;

    public void startTask(int num,InteAppalarmService inteAppalarmService) {
        this.Ltype = num;
        this.inteAppalarmService = inteAppalarmService;
        Runnable task = createTaskWithNumber(num);
        future = executor.schedule(task, 0, TimeUnit.SECONDS);
    }

    private Runnable createTaskWithNumber(int num) {
        return () -> {
            InteAppalarm inteAppalarm=exceptions(Ltype);
            inteAppalarm.setAlarmtime(Util.getNowTime());
            inteAppalarmService.save(inteAppalarm);
            int delay = new Random().nextInt(11) + 10;
            Runnable nextTask = createTaskWithNumber(num);
            future = executor.schedule(nextTask, delay, TimeUnit.SECONDS);
        };
    }
    public void stopTask() {

        if (future != null) {
            future.cancel(true);
            future = null;
        }
    }
    public  InteAppalarm exceptions(Integer type){
        InteAppalarm inteLog=new InteAppalarm();
        inteLog.setAlarmtype(type);
        Random random = new Random();
        int delay=0;
        switch (type) {
            case 1:
                delay = (int) (Math.random() * str1.length);
                inteLog.setAlarminfo(str1[delay]);
                break;
            case 2:
                delay = (int) (Math.random() * str2.length);
                inteLog.setAlarminfo(str2[delay]);
                break;
            case 3:
                delay = (int) (Math.random() * str3.length);
                inteLog.setAlarminfo(str3[delay]);
                break;
            case 4:
                delay = (int) (Math.random() * str4.length);
                inteLog.setAlarminfo(str4[delay]);
                break;
            case 5:
                delay = (int) (Math.random() * str5.length);
                inteLog.setAlarminfo(str5[delay]);
                break;
        }
        return inteLog;
    }
}

